package com.huweilong.commands;

import com.huweilong.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 下架书籍
 *
 * @author 是阿秋啊
 * @date 2022/04/09 13:34
 **/
public class PutOffCommand {
    public static void main(String[] args) throws SQLException {
        Scanner input = new Scanner(System.in);
        System.out.print("请输入书名：");
        String name = input.nextLine();
        System.out.print("请输入下架数量：");
        int count = input.nextInt();
        System.out.println("DEBUG:读取到用户输入的书名是 ｜" + name + "|");
        System.out.println("DEBUG:读取到用户输入的下架数量是 ｜" + count + "|");
        // 根据用户输入 和 总量关系，有两种操作，一种是删除，一种是更新
        Integer bid = null;
        Integer BookCount = null;
        Integer total = null;
        String BookName = null;
        try (Connection c = DBUtil.connection()) {
            // 先查询书籍
            String sql = "select bid, name,count, total from books where name = ?";
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setString(1, name);
                System.out.println("DEBUG:执行的SQl为：" + ps);
                try (ResultSet rs = ps.executeQuery()) {
                    if (rs.next()) {
                        bid = rs.getInt(1);
                        BookName = rs.getString(2);
                        BookCount = rs.getInt(3);
                        total = rs.getInt(4);
                        System.out.println("DEBUG：查询到的书状态为：｜" + bid + "|" + BookName + "|" + BookCount + "|" + total + "|");
                    }
                }
            }
        }
        // 判断书名是否正确
        if (bid == null) {
            System.out.println("没有此书！");
            return;
        }
        try (Connection c = DBUtil.connection()) {
            if (count >= total) {
                // 此时delete
                System.out.println("DEBUG：执行delete操作");
                String sql = "delete from books where bid = ?";
                try (PreparedStatement ps = c.prepareStatement(sql)) {
                    ps.setInt(1, bid);
                    System.out.println("DEBUG：执行SQL语句为："+ps);
                    ps.executeUpdate();
                }
            } else {
                // 使用update
                System.out.println("DEBUG：执行update操作");
                String sql = "update books set count = count - ?, total = total - ? where bid = ?";
                try (PreparedStatement ps = c.prepareStatement(sql)) {
                    ps.setInt(1, count);
                    ps.setInt(2, count);
                    ps.setInt(3, bid);
                    System.out.println("DEBUG：执行SQL语句为："+ps);
                    ps.executeUpdate();
                }
            }
        }
        System.out.println("下架成功！");
    }
}
